<?php
/**
 * ConsultController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 */

namespace Plugin\Consult\Controllers;
use Illuminate\Support\Facades\App;
use Beike\Admin\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Plugin\Consult\Services\YoudaoConsult;
use GatewayClient\Gateway;
use XdbSearcher;
use Illuminate\Support\Facades\Cache;
class ConsultController extends Controller
{
    public function index()
    {
        $service = Auth::user(); // 这里获取的是当前管理的
        // 分配一个客服账号根据id
        $old=DB::table('consult_service')->where('service_id',$service['id'])->first();
        if(json_decode(json_encode($old),true)){
            
        }else{
            DB::table('consult_service')->insertGetId(['service_id'=>$service['id'],'service_avatar'=>'/plugin/consult/image/logo.png','service_nickname'=>json_encode([['name'=>'English','code'=>'en','value'=>$service['name']],['name'=>'中文','code'=>'zh_cn','value'=>'客服']]),'service_describe'=>json_encode([['name'=>'English','code'=>'en','value'=>'hours of service 08:00-18:00'],['name'=>'中文','code'=>'zh_cn','value'=>'服务时间：08:00-18:00']]),'default_lang'=>'zh-CHS']);
        }
        $plugin = plugin('consult');
        $currentLocale = App::getLocale();
        $error   = '';

        $data = [
            'name'        => $plugin->getLocaleName(),
            'description' => $plugin->getLocaleDescription(),
            'error'       => $error,
            'lang' => $currentLocale,
        ];
        return view('Consult::admin.consult', $data);
    }
    public function consult_lang(){
        $list=DB::table('languages')->where('status',1)->get();
        return json_success(trans('common.get_success'), $list);
    }
    public function consult_setting(Request $request){
        $method = $request->method();
        $data=$request->all();
        switch ($method) {
            case 'PUT':
                if($data['type']=='t'){
                    $datum=['youdao_id'=>$data['youdao_id'],'youdao_key'=>$data['youdao_key']];
                }else{
                    $datum=['user_avatar'=>json_encode($data['user_avatar']),'your_first_reply'=>json_encode($data['your_first_reply']),'offline_prompt'=>json_encode($data['offline_prompt']),'service'=>$data['service'],'facebook'=>$data['facebook'],'messenger'=>$data['messenger'],'instagram'=>$data['instagram'],'whatsapp'=>$data['whatsapp'],'line'=>$data['line'],'snapchat'=>$data['snapchat'],'wecom'=>$data['wecom'],'tiktok'=>$data['tiktok'],'kwai'=>$data['kwai'],'vkontakte'=>$data['vkontakte'],'telegram'=>$data['telegram']];
                }
                $list=DB::table('consult_setting')->where('id',1)->update($datum);
                return json_success(trans('common.edit_success'));
            break;
            default:
                $list=DB::table('consult_setting')->where('id',1)->first();
                if(json_decode(json_encode($list),true)){
                    $list->user_avatar=json_decode($list->user_avatar,true);
                    $list->your_first_reply=json_decode($list->your_first_reply,true);
                    $list->offline_prompt=json_decode($list->offline_prompt,true);
                }else{
                    $list=[];
                }
                return json_success(trans('common.get_success'), $list);
            break;
        }
    }
    public function consult_batch_translate(Request $request){
        $data=$request->all();
        try {
            $service=DB::table('consult_setting')->where('id',1)->first();
            $te=0;
            if($service->youdao_id && $service->youdao_key){
                $s=new YoudaoConsult();
                if($data['translate_lang']=='all'){
                    // 翻译所有
                    foreach ($data['data'] as $k=>$v){
                        if($v['code']!=$data['current_lang']){
                            if($v['code']=='zh_cn'){
                                $v['code']='zh-CHS';
                            }
                            if($v['code']=='zh_hk'){
                                $v['code']='zh-CHT';
                            }
                            $q = $data['text'];
                            $from = $data['current_lang'];
                            $to = $v['code'];
                            // $vocab_id = "您的用户词表ID";
                        
                            $params = array('q' => $q,
                                'from' => $from,
                                'to' => $to,
                                // 'vocabId' => $vocab_id
                                );
                            $params = $s->add_auth_params($params, $service->youdao_id, $service->youdao_key);
                            $r = $s->do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
                            $arr=json_decode($r,true);
                            if($arr['errorCode']==0){
                                // 正确
                                $data['data'][$k]['value']=$arr['translation'][0];
                            }else{
                                $te=1;
                                $data['data'][$k]['value']='';
                            }
                        }
                    }
                    if($te){
                        return json_fail($arr['errorCode'], $data['data']);
                    }else{
                        return json_success(trans('common.get_success'), $data['data']);
                    }
                }else{
                    foreach ($data['data'] as $k=>$v){
                        if($v['code']==$data['translate_lang']){
                            if($v['code']=='zh_cn'){
                                $v['code']='zh-CHS';
                            }
                            if($v['code']=='zh_hk'){
                                $v['code']='zh-CHT';
                            }
                            $q = $data['text'];
                            $from = $data['current_lang'];
                            $to = $v['code'];
                            // $vocab_id = "您的用户词表ID";
                        
                            $params = array('q' => $q,
                                'from' => $from,
                                'to' => $to,
                                // 'vocabId' => $vocab_id
                                );
                            $params = $s->add_auth_params($params, $service->youdao_id, $service->youdao_key);
                            $r = $s->do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
                            $arr=json_decode($r,true);
                            if($arr['errorCode']==0){
                                // 正确
                                $data['data'][$k]['value']=$arr['translation'][0];
                            }else{
                                $te=1;
                                $data['data'][$k]['value']='';
                            }
                        }
                    }
                    if($te){
                        return json_fail($arr['errorCode'], $data['data']);
                    }else{
                        return json_success(trans('common.get_success'), $data['data']);
                    }
                }
            }else{
                return json_fail(trans('Consult::common.no_id_key'));
            }
            
        } catch (\Exception $e) {
            return json_fail($e->getMessage());
        }
    }
    public function consult_service(Request $request){
        $service = Auth::user();
        $method = $request->method();
        $data=$request->all();
        switch ($method) {
            case 'PUT':
                $datum=['service_avatar'=>$data['service_avatar'],'service_nickname'=>json_encode($data['service_nickname']),'service_describe'=>json_encode($data['service_describe']),'default_lang'=>$data['default_lang']];
                $list=DB::table('consult_service')->where('service_id',$service['id'])->update($datum);
                return json_success(trans('common.edit_success'));
            break;
            default:
                if(isset($data['info'])){
                    $currentLocale = App::getLocale();
                    $list=DB::table('consult_service')->where('service_id',$service['id'])->first();
                    $service_nickname=json_decode($list->service_nickname,true);
                    foreach ($service_nickname as $item) {  
                        if ($item['code'] === $currentLocale) {  
                            $service_nickname=$item['value'];
                            break;
                        }  
                    } 
                    return json_success(trans('common.get_success'), ['service_id'=>$list->service_id,'service_avatar'=>$list->service_avatar,'service_nickname'=>$service_nickname]);
                }
                $list=DB::table('consult_service')->where('service_id',$service['id'])->first();
                if(json_decode(json_encode($list),true)){
                    $list->service_nickname=json_decode($list->service_nickname,true);
                    $list->service_describe=json_decode($list->service_describe,true);
                }else{
                    $list=[];
                }
                return json_success(trans('common.get_success'), $list);
            break;
        }
    }
    public function consult_dialogue(Request $request){
        $service = Auth::user(); // 这里获取的是当前管理的
        $method = $request->method();
        $data=$request->all();
        switch ($method) {
            case 'POST':
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                $user_data=Db::table('consult_list')->where('user_id',$data['user_id'])->first();
                $user_data=json_decode(json_encode($user_data),true);
                if($data['role']===101){
                    // 已读
                    Db::table('consult_record')->where(['user_id'=>$data['user_id'],'type'=>1])->whereNull('read_time')->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                    Gateway::sendToUid('u_'.$user_data['user_id'], json_encode($data));
                    return json_success(trans('common.success'));
                }else{
                    
                }
                $translate='';
                $list=[];
                if($data['role']===1){
                    if($user_data['translate']){
                        //调用翻译
                        $thisData=$this->chat_translate(['text'=>$data['text'],'current'=>$user_data['service_lang'],'code'=>$user_data['user_lang']=='auto'?$user_data['user_language']:$user_data['user_lang']]);
                        if($thisData['code']===0){
                            
                        }elseif($thisData['code']===403){
                            // return json_fail(trans('Consult::common.no_id_key'));
                        }else{
                            // 记录错误
                        }
                        $translate=$thisData['text'];
                        $list=['type'=>2,'role'=>1,'user_id'=>$data['user_id'],'service_id'=>$user_data['service_id'],'text'=>$data['text'],'translate'=>$translate];
                    }
                }
                // Gateway::sendToAll(json_encode($data)); //发送所有人
                $data['translate']=$translate;
                Gateway::sendToUid('u_'.$user_data['user_id'], json_encode($data));
                // 判断是否需要翻译
                Db::table('consult_record')->insertGetId(['consult'=>$user_data['id'],'guid'=>$data['guid'],'user_id'=>$data['user_id'],'nickname'=>$data['nickname'],'avatar'=>$data['avatar'],'type'=>2,'role'=>$data['role'],'text'=>$data['text'],'content'=>json_encode($data['content']),'send_time'=>date('Y-m-d H:i:s'),'service_id'=>$user_data['service_id'],'ip'=>$request->ip(),'translate'=>$translate]);
                return json_success(trans('common.success'),$list);
            break;
            case 'PUT':
                // $user_data=Db::table('consult_list')->where('user_id',$data['user_id'])->first();
                // $user_data=json_decode(json_encode($user_data),true);
                // 绑定通信--并且判断用户是否在线
                if(isset($data['role']) && $data['role']===-1){
                    Db::table('consult_list')->where('user_id',$data['user_id'])->update(['state'=>0]);
                }else{
                    require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                    Gateway::$registerAddress = '127.0.0.1:1238';
                    Gateway::bindUid($data['client_id'], 's_'.$service['id']); //已经登陆的用户绑定对应id
                    // Gateway::sendToUid('u_'.$user_data['user_id'], json_encode(['role'=>100,'type'=>2]));
                }
                return json_success(trans('common.success'));
            break;
            case 'DELETE':
                $list=Db::table('consult_list')->where('id',$data['id'])->update(['status'=>0]);
                return json_success(trans('common.deleted_success'));
            break;
            case 'PATCH':
                // 撤回消息
                DB::table('consult_record')->where('guid',$data['guid'])->orderBy('id','desc')->update(['revocation'=>1]);
                // 撤回用户端数据
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                $datum=['role'=>-2,'type'=>2,'data'=>$data];
                Gateway::sendToUid('u_'.$data['user_id'], json_encode($datum));
                return json_success(trans('common.success'));
            break;
            default:
                if(isset($data['detail'])){
                    $list=Db::table('consult_list')
                        ->where('id',$data['detail'])
                        ->first();
                    $content=Db::table('consult_record')->where(['consult'=>$data['detail'],'revocation'=>0])->orderBy('id','desc')->paginate(30);
                    $content=json_decode(json_encode($content),true);
                    // 推送已读
                    require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                    Gateway::$registerAddress = '127.0.0.1:1238';
                    Gateway::sendToUid('u_'.$list->user_id, json_encode(['type'=>1,'role'=>101,'user_id'=>$list->user_id,'text'=>'']));
                    foreach ($content['data'] as $k => $r){
                        $content['data'][$k]['content']=json_decode($r['content']);
                    }
                    $list->contentDetail=array_reverse($content['data']);
                    // 把消息修改为已读
                    Db::table('consult_record')->where(['consult'=>$data['detail'],'type'=>1])->whereNull('read_time')->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                    return json_success(trans('common.get_success'), $list);
                }elseif(isset($data['id'])){
                    $content=Db::table('consult_record')->where('consult',$data['id'])->orderBy('id','desc')->paginate(30);
                    $content=json_decode(json_encode($content),true);
                    foreach ($content['data'] as $k => $r){
                        $content['data'][$k]['content']=json_decode($r['content']);
                    }
                    $array=array_reverse($content['data']);
                    $list=[];
                    $list['contentDetail']=$array;
                    return json_success(trans('common.get_success'), $list);
                }else{
                    // 获取所有数据
                    $list=Db::table('consult_list')->where(['service_id'=>$service['id'],'status'=>1])->orderBy('id','desc')->get();
                    $array=json_decode(json_encode($list),true);
                    if($array){
                        $content=Db::table('consult_record')->where('consult',$array[0]['id'])->orderBy('id','desc')->paginate(30);
                        $content=json_decode(json_encode($content),true);
                        foreach ($content['data'] as $k => $r){
                            $content['data'][$k]['content']=json_decode($r['content'],true)??[];
                            // $content['data'][$k]['contentDetail']['content']=json_decode($r['content'],true)??[];
                        }
                        require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                        Gateway::$registerAddress = '127.0.0.1:1238';
                        foreach ($array as $key=>$row){
                            // 获取最后一条消息
                            $message=Db::table('consult_record')->where(['consult'=>$row['id'],'revocation'=>0,'status'=>1])->orderBy('id','desc')->first();
                            $message=json_decode(json_encode($message),true);
                            if($message){
                                $message['content']=json_decode($message['content'],true);
                            }
                            // 判断用户是否在线
                            if($row['state']){
                                $user_state=Gateway::isUidOnline('u_'.$row['user_id']);
                                if($user_state){
                                    
                                }else{
                                    // 用户已经下线
                                    Db::table('consult_list')->where('id',$row['id'])->update(['state'=>0]);
                                    $array[$key]['state']=0;
                                }
                            }
                            // 查询最近最多99条数据-未读的用户数据
                            if($key===0){
                                // 第一条默认已读
                                // 更新读取时间
                                Db::table('consult_record')->where(['consult'=>$row['id'],'status'=>1,'type'=>1])->whereNull('read_time')->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                                $new=0;
                                // 推送已读
                                Gateway::sendToUid('u_'.$row['user_id'], json_encode(['type'=>1,'role'=>101,'user_id'=>$row['user_id'],'text'=>'']));
                            }else{
                                $new=Db::table('consult_record')->where(['consult'=>$row['id'],'status'=>1,'type'=>1])->whereNull('read_time')->orderBy('id','desc')->limit(20)->count();
                            }
                            $array[$key]['content']=$message;
                            $array[$key]['new']=$new;
                            $array[$key]['content_id']=$row['id'];
                            if($row['id']===$array[0]['id']){
                                $array[$key]['contentDetail']=array_reverse($content['data']);
                            }else{
                                $array[$key]['contentDetail']=[];
                            }
                        }
                    }
                    return json_success(trans('common.get_success'), $array);
                }
            break;
        }
    }
    public function consult_verbal(Request $request){
        // $user = Auth::user(); // 这里获取的是当前管理的
        // return response()->json($user);
        $method = $request->method();
        $data=$request->all();
        switch ($method) {
            case 'POST':
                $datum=['ask'=>$data['ask'],'answer'=>$data['answer'],'picture'=>json_encode($data['picture']),'created_at'=>date('Y-m-d H:i:s')];
                $list=DB::table('consult_verbal')->insert($datum);
                return json_success(trans('common.created_success'));
            break;
            case 'PUT':
                $datum=['ask'=>$data['ask'],'answer'=>$data['answer'],'picture'=>json_encode($data['picture']),'updated_at'=>date('Y-m-d H:i:s')];
                $list=DB::table('consult_verbal')->where('id',$data['id'])->update($datum);
                
                return json_success(trans('common.edit_success'));
            break;
            case 'DELETE':
                $list=DB::table('consult_verbal')->where('id',$data['id'])->delete();
                return json_success(trans('common.deleted_success'));
            break;
            default:
                if(isset($data['id'])){
                    $list=DB::table('consult_verbal')->where('id',$data['id'])->first();
                    $list->picture=json_decode($list->picture,true);
                }else{
                    $list=DB::table('consult_verbal')->orderBy('id','desc')->get();
                    $list=json_decode(json_encode($list),true);
                    foreach ($list as $key=>$v){
                        $list[$key]['picture']=json_decode($v['picture'],true);
                    }
                }
                return json_success(trans('common.get_success'), $list);
            break;
        }
    }
    public function consult_goods(Request $request){
        $currentLocale = App::getLocale();
        $data=$request->all();
        if(isset($data['product_id'])){
            if($data['user_lang']=='auto'){
                $data['user_lang']=$data['user_language	'];
            }
            if($data['user_lang']=='zh-CHS'){
                $data['user_lang']='zh_cn';
            }
            if($data['user_lang']=='zh-CHT'){
                $data['user_lang']='zh_hk';
            }
            $product = DB::table('products')
                ->leftJoin('product_descriptions', 'products.id', '=', 'product_descriptions.product_id')
                ->leftJoin('product_skus', 'products.id', '=', 'product_skus.product_id')
                ->where('products.id',$data['product_id'])
                ->where('product_descriptions.locale',$data['user_lang'])
                ->where('product_skus.is_default',1)
                ->select('products.*','product_descriptions.name','product_skus.price','product_skus.origin_price')->first();
                $list=json_decode(json_encode($product),true);
            $currency=DB::table('settings')->join('currencies', 'settings.value', '=', 'currencies.code')->where('settings.id',9)->select('symbol_left')->first();
            if(!empty($list)){
                $list['images']=json_decode($list['images'],true);
                $list['currency']=$currency->symbol_left;
            }
        }else{
            $product = DB::table('products')
                ->leftJoin('product_descriptions', 'products.id', '=', 'product_descriptions.product_id')
                ->leftJoin('product_skus', 'products.id', '=', 'product_skus.product_id')
                ->where('product_descriptions.locale',$currentLocale)
                ->where('product_skus.is_default',1)
                ->select('products.*','product_descriptions.name','product_skus.price','product_skus.origin_price')->get();
            $list=json_decode(json_encode($product),true);
            $currency=DB::table('settings')->join('currencies', 'settings.value', '=', 'currencies.code')->where('settings.id',9)->select('symbol_left')->first();
            foreach ($list as $key=>$v) {
                $list[$key]['images']=json_decode($v['images'],true);
                $list[$key]['currency']=$currency->symbol_left;
                $list[$key]['state']=1;
            }
        }
        return json_success(trans('common.get_success'), $list);
    }
    // 客户登陆后可查 customer_id
    public function consult_order(Request $request){
        // 只有登陆用户才返回订单
        $data=$request->all();
        $currentLocale = App::getLocale();
        $currentDate = date('Y-m-d'); // 获取今天的日期，格式为 YYYY-MM-DD  
        $fifteenDaysAgo = date('Y-m-d', strtotime('-15 days', strtotime($currentDate))); // 获取15天前的日期
        if($data['user_id']>0){
            // 获取今天的数据
            $product = DB::table('orders')
            ->leftJoin('order_products', 'orders.id', '=', 'order_products.order_id')
            ->leftJoin('currencies', 'orders.currency_code', '=', 'currencies.code')
            ->where('orders.customer_id',$data['user_id'])
            ->whereDate('orders.created_at', '>=', $fifteenDaysAgo)
            ->select('orders.*','order_products.name','order_products.image','order_products.price','order_products.quantity','currencies.symbol_left')->get();
        }else{
            $product=[];
        }
        $list=json_decode(json_encode($product),true);
        foreach ($list as $key=>$v) {
            $list[$key]['state']=1;
        }
        return json_success(trans('common.get_success'), $list);
    }
    // 客户登陆后可查 customer_id
    public function consult_footprint(Request $request){
        // user_id大于0的加载用户足迹，否则加载ip的
        $data=$request->all();
        // 这里返回客服的语言方便看
        $currentLocale = App::getLocale();
        if($data['user_id']>0){
            $product = DB::table('product_views')  
                ->leftJoin('products', 'product_views.product_id', '=', 'products.id')  
                ->leftJoin('product_descriptions', 'product_views.product_id', '=', 'product_descriptions.product_id')  
                ->leftJoin('product_skus', 'product_views.product_id', '=', 'product_skus.product_id')  
                ->where('product_views.customer_id', $data['user_id'])  
                ->where('product_descriptions.locale', $currentLocale)  
                ->where('product_skus.is_default', 1)  
                ->whereDate('product_views.created_at', date('Y-m-d'))  
                ->select(  
                    'product_views.product_id',  
                    DB::raw('MAX(product_views.created_at) as last_view_time'), //选择每个 product_id 最后一次查看的时间  
                    'products.images',  
                    'product_descriptions.name',  
                    'product_skus.price',  
                    'product_skus.origin_price'  
                )  
                ->groupBy('product_views.product_id', 'products.images', 'product_descriptions.name', 'product_skus.price', 'product_skus.origin_price')  
                ->get();
        }else{
            $product = DB::table('product_views')  
                ->leftJoin('products', 'product_views.product_id', '=', 'products.id')  
                ->leftJoin('product_descriptions', 'product_views.product_id', '=', 'product_descriptions.product_id')  
                ->leftJoin('product_skus', 'product_views.product_id', '=', 'product_skus.product_id')  
                ->where('product_views.customer_id','=',0)  
                ->where('product_views.customer_id', $data['user_id'])  
                ->where('product_views.ip','=',$request->ip())
                ->where('product_descriptions.locale', $currentLocale)  
                ->where('product_skus.is_default', 1)  
                ->whereDate('product_views.created_at', date('Y-m-d'))  
                ->select(  
                    'product_views.product_id',  
                    DB::raw('MAX(product_views.created_at) as last_view_time'), //选择每个 product_id 最后一次查看的时间  
                    'products.images',  
                    'product_descriptions.name',  
                    'product_skus.price',  
                    'product_skus.origin_price'  
                )  
                ->groupBy('product_views.product_id', 'products.images', 'product_descriptions.name', 'product_skus.price', 'product_skus.origin_price')  
                ->get();
        }
        $list=json_decode(json_encode($product),true);
        $currency=DB::table('settings')->join('currencies', 'settings.value', '=', 'currencies.code')->where('settings.id',9)->select('symbol_left')->first();
        foreach ($list as $key=>$v) {
            $list[$key]['images']=json_decode($v['images'],true);
            $list[$key]['currency']=$currency->symbol_left;
            $list[$key]['state']=1;
        }
        return json_success(trans('common.get_success'), $list);
    }
    public function consult_history(Request $request){
        $method = $request->method();
        $data=$request->all();
        switch ($method) {
            case 'DELETE':
                $list=DB::table('consult_list')->where('id',$data['id'])->delete();
                return json_success(trans('common.deleted_success'));
            break;
            default:
                if(isset($data['id'])){
                    $old=DB::table('consult_list')->where('id',$data['id'])->first();
                    $chat_array=json_decode(json_encode($old),true);
                    // 存在判断当前对应客服是否在线
                    $content=Db::table('consult_record')->where(['user_id'=>$chat_array['user_id']])->orderBy('id','desc')->paginate(30);
                    $content=json_decode(json_encode($content),true);
                    if(empty($content['data'])){
                        $chat_array['contentDetail']=[];
                    }else{
                        foreach ($content['data'] as $k => $r){
                            $content['data'][$k]['content']=json_decode($r['content']);
                        }
                        $chat_array['contentDetail']=array_reverse($content['data']);
                    }
                    $list=$chat_array;
                }else{
                    $list=DB::table('consult_list')->where('nickname','like','%'.$data['search'].'%')->orderBy('id','desc')->paginate($data['count']);
                }
                return json_success(trans('common.get_success'),$list);
            break;
        }
    }
    // 转接
    public function consult_transfer(Request $request){
        $service = Auth::user();
        $data=$request->all();
        $method = $request->method();
        switch ($method) {
            case 'PUT':
                // 转接给客服
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                if(Gateway::isUidOnline('s_'.$data['new_service']['service_id'])){
                    Db::table('consult_list')->where('user_id',$data['old_service']['user_id'])->update(['service_id'=>$data['new_service']['service_id']]); //更换客服
                    // 推送新的客服给用户
                    $service_nickname='';
                    if($data['old_service']['user_lang']=='auto'){
                        $data['old_service']['user_lang']=$data['old_service']['user_language'];
                    }
                    if($data['old_service']['user_lang']=='zh-CHS'){
                        $data['old_service']['user_lang']='zh_cn';
                    }
                    if($data['old_service']['user_lang']=='zh-CHT'){
                        $data['old_service']['user_lang']='zh_hk';
                    }
                    foreach ($data['new_service']['service_nickname'] as $item) {  
                        if ($item['code'] === $data['old_service']['user_lang']) {  
                            $service_nickname=$item['value'];
                            break;
                        }  
                    } 
                    $service_describe='';
                    foreach ($data['new_service']['service_describe'] as $item) {  
                        if ($item['code'] === $data['old_service']['user_lang']) {  
                            $service_describe=$item['value'];
                            break;
                        }  
                    } 
                    $user_data = json_encode(['role'=>102,'user_id'=>$data['old_service']['user_id'],'service_id'=>$data['new_service']['service_id'],'service_info'=>['service_nickname'=>$service_nickname,'service_describe'=>$service_describe,'service_avatar'=>$data['new_service']['service_avatar']]]);
                    Gateway::sendToUid('u_'.$data['old_service']['user_id'], $user_data);
                    // 推送给新的客服
                    
                    $chat_array=Db::table('consult_list')->where('user_id',$data['old_service']['user_id'])->first();
                    $chat_array=json_decode(json_encode($chat_array),true);
                    // 在线
                    $chat_array['state']=1;
                    $chat_array['new']=0;
                    $content=Db::table('consult_record')->where(['user_id'=>$chat_array['user_id']])->get();
                    $content=json_decode(json_encode($content),true);
                    if(empty($content)){
                        $chat_array['contentDetail']=[];
                    }else{
                        foreach ($content as $k => $r){
                            $content[$k]['contentDetail']['content']=json_decode($r['content']);
                        }
                        $chat_array['contentDetail']=$content;
                    }
                    $service_data=json_encode(['role'=>102,'type'=>1,'data'=>$chat_array]);
                    Gateway::sendToUid('s_'.$data['new_service']['service_id'], $service_data);
                    return json_success(trans('Consult::common.successfully_transferred'));
                }else{
                    return json_fail(trans('Consult::common.transfer_failure'));
                }
            break;
            default:
                $list=DB::table('consult_service')->where('service_id', '<>', $service['id'])->join('admin_users', 'consult_service.service_id', '=', 'admin_users.id')->select('consult_service.*','admin_users.name')->get();
                // 判断客服是否在线
                $array=json_decode(json_encode($list),true);
                $arr=[];
                if($array){
                    require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                    Gateway::$registerAddress = '127.0.0.1:1238';
                    foreach ($array as $key=>$v){
                        $array[$key]['service_nickname']=json_decode($v['service_nickname'],true);
                        $array[$key]['service_describe']=json_decode($v['service_describe'],true);
                        if(Gateway::isUidOnline('s_'.$v['service_id'])){
                            $array[$key]['state']=1;
                        }else{
                            $array[$key]['state']=0;
                        }
                    }
                    $arr=$array;
                }else{
                    $arr=[];
                }
                return json_success(trans('common.get_success'),$arr);
            break;
        }
    }
    // 切换翻译
    public function consult_switch_translate(Request $request){
        $data=$request->all();
        $list=DB::table('consult_list')->where('id',$data['id'])->update(['user_lang'=>$data['user_lang'],'service_lang'=>$data['service_lang'],'user_language'=>$data['user_language'],'translate'=>$data['translate'],'robot'=>$data['robot'],'remark'=>$data['remark']]);
        return json_success(trans('common.edit_success'),$list);
    }
    public function consult_ping(Request $request){
        return json_success(trans('common.get_success'),['status'=>'ok']);
    }
    public function advisory(){
        $plugin = plugin('consult');
        $currentLocale = App::getLocale();
        $error   = '';

        $data = [
            'name'        => $plugin->getLocaleName(),
            'description' => $plugin->getLocaleDescription(),
            'error'       => $error,
            'lang' => $currentLocale,
        ];

        return view('Consult::shop.advisory', $data);
    }
    public function advisory_setting(){
        $user = current_customer();
        $setting=DB::table('consult_setting')->where('id',1)->select('service','facebook','messenger','instagram','whatsapp','line','snapchat','wecom','tiktok','kwai','vkontakte','telegram')->first();
        if($user){
            $setting->login=1;
        }else{
            $setting->login=0;
        }
        return json_success(trans('common.get_success'), $setting);
    }
    private function chat_translate($datum){
        $service=DB::table('consult_setting')->where('id',1)->first();
        if($service->youdao_id && $service->youdao_key){
            $s=new YoudaoConsult();
                $q = $datum['text'];
                $from = $datum['current'];
                $to = $datum['code'];
                // $vocab_id = "您的用户词表ID";
            
                $params = array('q' => $q,
                    'from' => $from,
                    'to' => $to,
                    // 'vocabId' => $vocab_id
                    );
                $params = $s->add_auth_params($params, $service->youdao_id, $service->youdao_key);
                $r = $s->do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
                $arr=json_decode($r,true);
                if($arr['errorCode']==0){
                    // 正确
                    return ['code'=>0,'text'=>$arr['translation'][0]];
                }else{
                    return ['code'=>404,'text'=>''];
                }
        }else{
            // 未配置翻译
            return ['code'=>403,'text'=>''];
        }
    }
    // 客服分配
    private function service_distribution(){
        $list=DB::table('consult_service')->select('service_id')->get();
        $arr=json_decode(json_encode($list),true);
        require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
        Gateway::$registerAddress = '127.0.0.1:1238';
        $key='consult_service_sort_reception';
        // Cache::forget($key);
        $service=Cache::get($key);
        $service_id=0;
        if($service){
            $startIndex = -1;  
            $old=0;  
            // 找到 $service_id 的初始位置  
            for ($i = 0; $i < count($arr); $i++) {  
                if ($arr[$i]['service_id'] == $service) {  
                    $startIndex = $i;  
                    $old=1; 
                    break;  
                }  
            }  
            if($old){
                // 从 $startIndex+1 开始遍历数组并打印结果  
                for ($i = ($startIndex + 1) % count($arr); $i != $startIndex; $i = ($i + 1) % count($arr)) {  
                    $status=Gateway::isUidOnline('s_'.$arr[$i]['service_id']);
                    if($status){
                        $service_id=$arr[$i]['service_id'];
                        Cache::put($key,$arr[$i]['service_id']);
                        break;
                    }
                }  
            }else{
                Cache::forget($key);
                foreach($arr as $k=>$v){
                    $status=Gateway::isUidOnline('s_'.$v['service_id']);
                    if($status){
                        $service_id=$v['service_id'];
                        Cache::put($key,$v['service_id']);
                        break;
                    }
                }
            }
        }else{
            foreach($arr as $k=>$v){
                $status=Gateway::isUidOnline('s_'.$v['service_id']);
                if($status){
                    $service_id=$v['service_id'];
                    Cache::put($key,$v['service_id']);
                    break;
                }
            }
        }
        if($service_id){
            return ['service_id'=>$service_id,'state'=>1];
        }else{
            return ['service_id'=>$arr[0]['service_id'],'state'=>0];
        }
    }
    public function advisory_dialogue(Request $request){
        $method = $request->method();
        $currentLocale = App::getLocale();
        $currentLocaleUser=$currentLocale;
        if($currentLocale=='zh_cn'){
            $currentLocaleUser='zh-CHS';
        }
        if($currentLocale=='zh_hk'){
            $currentLocaleUser='zh-CHT';
        }
        $data=$request->all();
        $user = current_customer();
        switch ($method) {
            case 'POST':
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                $user_data=Db::table('consult_list')->where('user_id',$data['user_id'])->first();
                $user_data=json_decode(json_encode($user_data),true);
                if($data['role']===101){
                    // 已读
                    Db::table('consult_record')->where(['user_id'=>$data['user_id'],'type'=>2])->whereNull('read_time')->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                    Gateway::sendToUid('s_'.$user_data['service_id'], json_encode($data));
                    return json_success(trans('common.success'));
                }else{
                    
                }
                // 判断是否需要翻译
                $translate='';
                if($data['role']===1){
                    if($user_data['translate']){
                        //调用翻译
                        $thisData=$this->chat_translate(['text'=>$data['text'],'current'=>$user_data['user_lang'],'code'=>$user_data['service_lang']]);
                        if($thisData['code']===0){
                            
                        }elseif($thisData['code']===403){
                            // return json_fail(trans('Consult::common.no_id_key'));
                        }else{
                            // 记录错误
                        }
                        $translate=$thisData['text'];
                    }
                }
                // Gateway::sendToAll(json_encode($data)); //发送所有人
                $data['translate']=$translate;
                Gateway::sendToUid('s_'.$user_data['service_id'], json_encode($data));
                // Gateway::sendToClient($client_id, $data); //发送指定id客服
                Db::table('consult_record')->insertGetId(['consult'=>$user_data['id'],'guid'=>$data['guid'],'user_id'=>$data['user_id'],'nickname'=>$data['nickname'],'avatar'=>$data['avatar'],'type'=>1,'role'=>$data['role'],'text'=>$data['text'],'content'=>json_encode($data['content']),'send_time'=>date('Y-m-d H:i:s'),'service_id'=>$user_data['service_id'],'ip'=>$request->ip(),'translate'=>$translate]);
                // 判断是否配置首句
                $setting_first=Db::table('consult_setting')->where('id',1)->select('your_first_reply')->first();
                $setting_first_array=json_decode($setting_first->your_first_reply,true);
                $first_text='';
                foreach ($setting_first_array as $item) {  
                    if ($item['code'] === $currentLocale) {  
                        $first_text=$item['value'];
                        break;
                    }  
                } 
                $first_service_text='';
                $service_lang_text='';
                if($user_data['service_lang']=='zh-CHS'){
                    $service_lang_text='zh_cn';
                }
                if($user_data['service_lang']=='zh-CHT'){
                    $service_lang_text='zh_hk';
                }
                foreach ($setting_first_array as $item) {  
                    if ($item['code'] === $service_lang_text) {  
                        $first_service_text=$item['value'];
                        break;
                    }  
                } 
                // 判断是否在线在线才触发
                if(Gateway::isUidOnline('s_'.$user_data['service_id'])){
                    if(!empty($first_text)){
                        // 判断是否第一句话
                        $record_count=Db::table('consult_record')->where(['user_id'=>(string)$data['user_id'],'type'=>2])->count();
                        if($record_count===0){
                            // 写入数据-这是客服数据
                            
                            $service_datum=Db::table('consult_service')->where(['service_id'=>$user_data['service_id']])->first();
                            $service_datum_array=json_decode(json_encode($service_datum),true);
                            $service_datum_array_nickname=json_decode($service_datum->service_nickname,true);
                            $service_text='';
                            foreach ($service_datum_array_nickname as $item) {  
                                if ($item['code'] === $currentLocale) {  
                                    $service_text=$item['value'];
                                    break;
                                }  
                            } 
                            Db::table('consult_record')->insertGetId(['consult'=>$user_data['id'],'guid'=>$data['guid'],'user_id'=>$data['user_id'],'nickname'=>$service_text,'avatar'=>$service_datum_array['service_avatar'],'type'=>2,'role'=>1,'text'=>$first_service_text,'content'=>json_encode($data['content']),'send_time'=>date('Y-m-d H:i:s'),'service_id'=>$user_data['service_id'],'ip'=>$request->ip(),'translate'=>$first_text]);
                            // 推送数据
                            $new_data_first=$data;
                            $new_data_first['type']=2;
                            $new_data_first['role']=1;
                            $new_data_first['text']=$first_service_text;
                            $new_data_first['translate']=$first_text;
                            $new_data_first['avatar']=$service_datum_array['service_avatar'];
                            $new_data_first['nickname']=$service_text;
                            Gateway::sendToUid('s_'.$user_data['service_id'], json_encode($new_data_first));
                            Gateway::sendToUid('u_'.$data['user_id'], json_encode($new_data_first));
                        }
                    }
                }
                return json_success(trans('common.success'));
            break;
            case 'PUT':
                if(!$user){
                    $user['id']=$data['user_id'];
                }
                $user_data=Db::table('consult_list')->where('user_id',(string)$user['id'])->first();
                $user_data=json_decode(json_encode($user_data),true);
                // 绑定通信--并且判断客服是否在线
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                Gateway::bindUid($data['client_id'], 'u_'.$user['id']); //已经登陆的用户绑定对应id
                // 推送告诉客服在线
                $chat_array=$user_data;
                // 在线
                $chat_array['state']=1;
                $chat_array['new']=0;
                $content=Db::table('consult_record')->where(['user_id'=>$chat_array['user_id']])->orderBy('id','desc')->paginate(30);
                $content=json_decode(json_encode($content),true);
                if(empty($content)){
                    $chat_array['contentDetail']=[];
                }else{
                    foreach ($content['data'] as $k => $r){
                        $content['data'][$k]['contentDetail']['content']=json_decode($r['content']);
                    }
                    $chat_array['contentDetail']=array_reverse($content['data']);
                }
                Gateway::sendToUid('s_'.$user_data['service_id'], json_encode(['role'=>100,'type'=>1,'data'=>$chat_array]));
                Db::table('consult_list')->where('user_id',(string)$user['id'])->update(['state'=>1]);
                $status=Gateway::isUidOnline('s_'.$user_data['service_id']);
                if($status){
                    $state=1;
                    $d=[];
                }else{
                    // 客服不在线
                    $setting=DB::table('consult_setting')->where('id',1)->first();
                    $offline_prompt=json_decode($setting->offline_prompt,true);
                    $offline_text='';
                    foreach ($offline_prompt as $item) {  
                        if ($item['code'] === $currentLocale) {  
                            $offline_text=$item['value'];
                            break;
                        }  
                    } 
                    $service=DB::table('consult_service')->where('service_id',$user_data['service_id'])->select('service_avatar','service_nickname','service_describe')->first();
                    $service_nickname=json_decode($service->service_nickname,true);
                    foreach ($service_nickname as $item) {  
                        if ($item['code'] === $currentLocale) {  
                            $service->service_nickname=$item['value'];
                            break;
                        }  
                    } 
                    $service_offline=DB::table('consult_service')->where('service_id',$chat_array['service_id'])->first();
                    $service_offline=json_decode(json_encode($service_offline),true);
                    $time=date('Y-m-d H:i:s');
                    $d=['type'=>2,'role'=>1,'user_id'=>(string)$user['id'],'text'=>$offline_text,'service_id'=>$user_data['service_id'],'read_time'=>$time,'send_time'=>$time,'nickname'=>$service->service_nickname,'avatar'=>$service->service_avatar,'content'=>[]];
                    $state=0;
                }
                return json_success(trans('common.success'),['state'=>$state,'data'=>$d]);
            break;
            case 'PATCH':
                // 合并访客数据
                $old=Db::table('consult_list')->where('user_id',(string)$data['user_id'])->first();
                // 合并数据最好判断是否大于100条大于的忽略
                // 获取用户的上级列表id
                $new=Db::table('consult_list')->where('user_id',user['id'])->first();
                $list=Db::table('consult_record')->where('consult',$old->id)->update(['user_id'=>(string)$user['id'],'consult'=>$new->id]);
                // 判断客服在线则移除客服端并赋值合并后的组
                Db::table('consult_list')->where('user_id',(string)$data['user_id'])->delete(); //移除访客
                // 推送给客服数据已经移除
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                // 移除旧的数据
                Gateway::sendToUid('s_'.$old->service_id, json_encode(['role'=>104,'type'=>2,'user_id'=>(string)$old->user_id,nickname=>$old->nickname]));
                return json_success(trans('common.success'));
            break;    
            default:
                $region='';
                $user_id='';
                $detail=[];
                if($user && isset($data['detail'])){
                    if($data['detail'] == $user['id']){
                        // 仅登陆用户可查历史记录
                        $content=Db::table('consult_record')->where(['user_id'=>$data['detail'],'revocation'=>0])->orderBy('id','desc')->paginate(30);
                        $content=json_decode(json_encode($content),true);
                        foreach ($content['data'] as $k => $r){
                            $content['data'][$k]['content']=json_decode($r['content']);
                        }
                        $array=array_reverse($content['data']);
                        $detail['contentDetail']=$array;
                    }
                    return json_success(trans('common.success'),$detail);
                }
                if(isset($data['detail'])){
                    return json_success(trans('common.success'),$detail);
                }
                try {
                    require_once dirname(__DIR__, 1) . '/Ip/XdbSearcher.class.php';
                    $searcher = XdbSearcher::newWithFileOnly(dirname(__DIR__, 1) . '/Ip/ip2region.xdb');
                    $r = $searcher->search($request->ip());
                    $l=str_replace("|0", "", $r);
                    $s=explode('|',$l);
                    $region=$s[0];
                } catch (Exception $e) {
                }
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                // 判断是否登陆
                if($user){
                    // 判断是否在列表
                    $old=DB::table('consult_list')->where('user_id',(string)$user['id'])->select('id','user_id','service_id','nickname','avatar','user_lang','service_lang','user_language')->first();
                    $chat_array=json_decode(json_encode($old),true);
                    if($chat_array){
                        // 存在更新ip和地理位置
                        $f=DB::table('admin_users')->where('id',$chat_array['service_id'])->first();
                        $this_user_lang=$f->locale;
                        if($this_user_lang!='zh_cn'){
                            if($this_user_lang=='zh_cn'){
                                $this_user_lang='zh-CHS';
                            }
                            if($this_user_lang=='zh_hk'){
                                $this_user_lang='zh-CHT';
                            }
                            $thisData=$this->chat_translate(['text'=>$region,'current'=>'zh-CHS','code'=>$this_user_lang=='zh_hk'?'zh-CHT':$this_user_lang]);
                            if($thisData['code']===0){
                                
                            }elseif($thisData['code']===403){
                                // return json_fail(trans('Consult::common.no_id_key'));
                            }else{
                                // 记录错误
                            }
                            $region=$thisData['text'];
                        }
                        $chat_array['status']=1;
                        $avatar_new=$user['avatar']?$user['avatar']:$chat_array['avatar'];
                        $datum_list=['ip'=>$request->ip(),'address'=>$region,'status'=>1,'nickname'=>$user['name'],'avatar'=>$avatar_new,'user_lang'=>$chat_array['user_lang']=='auto'?'auto':$currentLocaleUser,'user_language'=>$currentLocaleUser];
                        DB::table('consult_list')->where('user_id',(string)$user['id'])->update($datum_list);
                        // 存在判断当前对应客服是否在线
                        $content=Db::table('consult_record')->where(['user_id'=>(string)$user['id'],'revocation'=>0])->orderBy('id','desc')->paginate(30);
                        $content=json_decode(json_encode($content),true);
                        if(empty($content['data'])){
                            $chat_array['contentDetail']=[];
                        }else{
                            // 数据不为空-设置已读
                            Db::table('consult_record')->where(['user_id'=>$chat_array['user_id'],'type'=>2])->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                            foreach ($content['data'] as $k => $r){
                                $content['data'][$k]['content']=json_decode($r['content']);
                                // $content[$k]['contentDetail']['content']=json_decode($r['content']);
                            }
                            $chat_array['contentDetail']=array_reverse($content['data']);;
                        }
                        // 判断客服是否在线不在线切换
                        $old_service=Gateway::isUidOnline('s_'.$chat_array['service_id']);
                        if($old_service){
                            
                        }else{
                            $new_service=$this->service_distribution();
                            if($new_service['state']){
                                // 有客服在线分配
                                DB::table('consult_list')->where('user_id',(string)$user['id'])->update(['service_id'=>$new_service['service_id']]);
                                $chat_array['service_id']=$new_service['service_id'];
                            }
                        }
                        $list=$chat_array;
                    }else{
                        $setting=Db::table('consult_setting')->where('id',1)->first();
                        $avatar=json_decode($setting->user_avatar,true);
                        // 获取随机键  
                        $randomKey = array_rand($avatar);  
                          
                        // 获取随机键对应的数组元素  
                        $randomData = $avatar[$randomKey]; 
                        
                        $f=DB::table('admin_users')->where('id',1)->first();
                        $this_user_lang=$f->locale;
                        if($this_user_lang!='zh_cn'){
                            if($this_user_lang=='zh_cn'){
                                $this_user_lang='zh-CHS';
                            }
                            if($this_user_lang=='zh_hk'){
                                $this_user_lang='zh-CHT';
                            }
                            $thisData=$this->chat_translate(['text'=>$region,'current'=>'zh-CHS','code'=>$this_user_lang=='zh_hk'?'zh-CHT':$this_user_lang]);
                            if($thisData['code']===0){
                                
                            }elseif($thisData['code']===403){
                                // return json_fail(trans('Consult::common.no_id_key'));
                            }else{
                                // 记录错误
                            }
                            $region=$thisData['text'];
                        }
                        $new_service=$this->service_distribution();
                        // 不存在接入对话新建分配在线客服
                        $service_default=DB::table('consult_service')->where('service_id',$new_service['service_id'])->first();
                        $datum=['user_id'=>(string)$user['id'],'service_id'=>$new_service['service_id'],'avatar'=>$user['avatar']?$user['avatar']:$randomData['url'],'nickname'=>$user['name'],'ip'=>$request->ip(),'address'=>$region,'user_lang'=>$currentLocaleUser,'service_lang'=>$service_default->default_lang,'user_language'=>$currentLocaleUser,'created_at'=>date('Y-m-d H:i:s')];
                        $new_list=DB::table('consult_list')->insertGetId($datum);
                        $list=DB::table('consult_list')->where('id',$new_list)->first();
                        $list->contentDetail=[];
                        $list=json_decode(json_encode($list),true);
                    }
                }else{
                    // 未登录
                    if($data['user_id']){
                        $old=DB::table('consult_list')->where('user_id',$data['user_id'])->select('id','user_id','service_id','nickname','avatar','user_lang','service_lang','user_language')->first();
                        $chat_array=json_decode(json_encode($old),true);
                        if($chat_array){
                            // 存在更新ip和地理位置
                            $f=DB::table('admin_users')->where('id',$chat_array['service_id'])->first();
                            $this_user_lang=$f->locale;
                            if($this_user_lang!='zh_cn'){
                                if($this_user_lang=='zh_cn'){
                                    $this_user_lang='zh-CHS';
                                }
                                if($this_user_lang=='zh_hk'){
                                    $this_user_lang='zh-CHT';
                                }
                                $thisData=$this->chat_translate(['text'=>$region,'current'=>'zh-CHS','code'=>$this_user_lang=='zh_hk'?'zh-CHT':$this_user_lang]);
                                if($thisData['code']===0){
                                    
                                }elseif($thisData['code']===403){
                                    // return json_fail(trans('Consult::common.no_id_key'));
                                }else{
                                    // 记录错误
                                }
                                $region=$thisData['text'];
                            }
                            $chat_array['status']=1;
                            $updateConsult=['ip'=>$request->ip(),'address'=>$region,'status'=>1,'user_lang'=>$chat_array['user_lang']=='auto'?'auto':$currentLocaleUser,'user_language'=>$currentLocaleUser];
                            DB::table('consult_list')->where('user_id',$chat_array['user_id'])->update($updateConsult);
                            // 存在判断当前对应客服是否在线
                            $content=Db::table('consult_record')->where(['user_id'=>$chat_array['user_id'],'revocation'=>0])->orderBy('id','desc')->paginate(30);
                            $content=json_decode(json_encode($content),true);
                            if(empty($content['data'])){
                                $chat_array['contentDetail']=[];
                            }else{
                                // 数据不为空-设置已读
                                Db::table('consult_record')->where(['user_id'=>$chat_array['user_id'],'type'=>2])->orderBy('id','desc')->limit(20)->update(['read_time'=>date('Y-m-d H:i:s')]);
                                // 推送已读
                                Gateway::sendToUid('s_'.$chat_array['service_id'], json_encode(['type'=>2,'role'=>101,'user_id'=>$chat_array['user_id'],'text'=>'']));
                                foreach ($content['data'] as $k => $r){
                                    $content['data'][$k]['content']=json_decode($r['content']);
                                    // $content[$k]['contentDetail']['content']=json_decode($r['content']);
                                }
                                $chat_array['contentDetail']=array_reverse($content['data']);
                            }
                            // 判断客服是否在线不在线切换
                            $old_service=Gateway::isUidOnline('s_'.$chat_array['service_id']);
                            if($old_service){
                                
                            }else{
                                $new_service=$this->service_distribution();
                                if($new_service['state']){
                                    // 有客服在线分配
                                    DB::table('consult_list')->where('user_id',$chat_array['user_id'])->update(['service_id'=>$new_service['service_id']]);
                                    $chat_array['service_id']=$new_service['service_id'];
                                }
                            }
                            $list=$chat_array;
                            $user_id=$chat_array['user_id'];
                        }else{
                            $user_guid=time().'u'.mt_rand(111111,999999);
                            $setting=Db::table('consult_setting')->where('id',1)->first();
                            $avatar=json_decode($setting->user_avatar,true);
                            // 获取随机键  
                            $randomKey = array_rand($avatar);  
                              
                            // 获取随机键对应的数组元素  
                            $randomData = $avatar[$randomKey]; 
                            $f=DB::table('admin_users')->where('id',1)->first();
                            $this_user_lang=$f->locale;
                            if($this_user_lang!='zh_cn'){
                                if($this_user_lang=='zh_cn'){
                                    $this_user_lang='zh-CHS';
                                }
                                if($this_user_lang=='zh_hk'){
                                    $this_user_lang='zh-CHT';
                                }
                                $thisData=$this->chat_translate(['text'=>$region,'current'=>'zh-CHS','code'=>$this_user_lang=='zh_hk'?'zh-CHT':$this_user_lang]);
                                if($thisData['code']===0){
                                    
                                }elseif($thisData['code']===403){
                                    // return json_fail(trans('Consult::common.no_id_key'));
                                }else{
                                    // 记录错误
                                }
                                $region=$thisData['text'];
                            }
                            $new_service=$this->service_distribution();
                            // 不存在接入对话新建分配在线客服
                            $service_default=DB::table('consult_service')->where('service_id',$new_service['service_id'])->first();
                            $datum=['user_id'=>$user_guid,'service_id'=>$new_service['service_id'],'avatar'=>$randomData['url'],'nickname'=>date('mdHis').mt_rand(111,999),'ip'=>$request->ip(),'address'=>$region,'user_lang'=>$currentLocaleUser,'service_lang'=>$service_default->default_lang,'user_language'=>$currentLocaleUser,'created_at'=>date('Y-m-d H:i:s')];
                            $new_list=DB::table('consult_list')->insertGetId($datum);
                            $list=DB::table('consult_list')->where('id',$new_list)->first();
                            $list->contentDetail=[];
                            $list=json_decode(json_encode($list),true);
                            $user_id=$user_guid;
                        }
                    }else{
                        $user_guid=time().'u'.mt_rand(111111,999999);
                        $setting=Db::table('consult_setting')->where('id',1)->first();
                        $avatar=json_decode($setting->user_avatar,true);
                        // 获取随机键  
                        $randomKey = array_rand($avatar);  
                          
                        // 获取随机键对应的数组元素  
                        $randomData = $avatar[$randomKey]; 
                        
                        $f=DB::table('admin_users')->where('id',1)->first();
                        $this_user_lang=$f->locale;
                        if($this_user_lang!='zh_cn'){
                            if($this_user_lang=='zh_cn'){
                                $this_user_lang='zh-CHS';
                            }
                            if($this_user_lang=='zh_hk'){
                                $this_user_lang='zh-CHT';
                            }
                            $thisData=$this->chat_translate(['text'=>$region,'current'=>'zh-CHS','code'=>$this_user_lang=='zh_hk'?'zh-CHT':$this_user_lang]);
                            if($thisData['code']===0){
                                
                            }elseif($thisData['code']===403){
                                // return json_fail(trans('Consult::common.no_id_key'));
                            }else{
                                // 记录错误
                            }
                            $region=$thisData['text'];
                        }
                        $new_service=$this->service_distribution();
                        // 不存在接入对话新建分配在线客服
                        $service_default=DB::table('consult_service')->where('service_id',$new_service['service_id'])->first();
                        $datum=['user_id'=>$user_guid,'service_id'=>$new_service['service_id'],'avatar'=>$randomData['url'],'nickname'=>date('mdHis').mt_rand(111,999),'ip'=>$request->ip(),'address'=>$region,'user_lang'=>$currentLocaleUser,'service_lang'=>$service_default->default_lang,'user_language'=>$currentLocaleUser,'created_at'=>date('Y-m-d H:i:s')];
                        $new_list=DB::table('consult_list')->insertGetId($datum);
                        $list=DB::table('consult_list')->where('id',$new_list)->first();
                        $list->contentDetail=[];
                        $list=json_decode(json_encode($list),true);
                        $user_id=$user_guid;
                    }
                }
                $service=DB::table('consult_service')->where('service_id',$list['service_id'])->select('service_avatar','service_nickname','service_describe')->first();
                $service_nickname=json_decode($service->service_nickname,true);
                $service_describe=json_decode($service->service_describe,true);
                foreach ($service_nickname as $item) {  
                    if ($item['code'] === $currentLocale) {  
                        $service->service_nickname=$item['value'];
                        break;
                    }  
                } 
                foreach ($service_describe as $item) {  
                    if ($item['code'] === $currentLocale) {  
                        $service->service_describe=$item['value'];
                        break;
                    }  
                } 
                // 推送已读
                require_once dirname(__DIR__, 1) . '/Worker/GatewayClient/Gateway.php';
                Gateway::$registerAddress = '127.0.0.1:1238';
                Gateway::sendToUid('s_'.$list['service_id'], json_encode(['type'=>2,'role'=>101,'user_id'=>$list['user_id'],'text'=>'']));
                return json_success(trans('common.get_success'), ['service'=>$service,'content'=>$list,'user_id'=>$user_id]);
            break;
        }
    }
    public function advisory_product(Request $request){
        $currentLocale = App::getLocale();
        $data=$request->all();
        $product = DB::table('products')
            ->leftJoin('product_descriptions', 'products.id', '=', 'product_descriptions.product_id')
            ->leftJoin('product_skus', 'products.id', '=', 'product_skus.product_id')
            ->where('products.id',$data['id'])
            ->where('product_descriptions.locale',$currentLocale)
            ->where('product_skus.is_default',1)
            ->select('products.*','product_descriptions.name','product_skus.price','product_skus.origin_price')->first();
            $list=json_decode(json_encode($product),true);
        $currency=DB::table('settings')->join('currencies', 'settings.value', '=', 'currencies.code')->where('settings.id',9)->select('symbol_left')->first();
        if(!empty($list)){
            $list['images']=json_decode($list['images'],true);
            $list['currency']=$currency->symbol_left;
        }
        return json_success(trans('common.success'),$list);
    }
}